package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.MyteamTypeNameAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.fragment.DynamicFragment;
import com.runen.infinitemovement.fragment.MemberFragment;
import com.runen.infinitemovement.fragment.NoticeFragment;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.MemberEntity;
import com.runen.infinitemovement.model.entity.PictrueEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.UiUtil;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.AddCorpsPoppupWindow;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.infinitemovement.widget.popupwind.HandOverTeamPoppupWindow;
import com.runen.infinitemovement.widget.popupwind.KickOutPopupWindow;
import com.runen.infinitemovement.widget.popupwind.TeamPopupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;
import com.zhihu.matisse.Matisse;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class MyTeamActivityV2 extends BaseActivity {
    @BindView(R.id.rv_title)
    RecyclerView rvTitle;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.ll_title)
    LinearLayout ll_title;
    @BindView(R.id.tv_team_count)
    TextView tv_team_count;
    @BindView(R.id.tv_team_hz)
    TextView tv_team_hz;
    @BindView(R.id.tv_team_totalContribute)
    TextView tv_team_totalContribute;
    @BindView(R.id.rci_team_logo)
    RoundedCornersImage rci_team_logo;
    @BindView(R.id.tv_team_name)
    TextView tv_team_name;
    @BindView(R.id.top_btn_right)
    Button top_btn_right;
    private MyteamTypeNameAdapter myteamTypeNameAdapter;
    private String[] typeNames = new String[]{"成员", "动态", "公告"};
    private List<String> stringList = new ArrayList<>();

    private String targetId = "";
    public MemberEntity.DataBean entity;
    private boolean isTeamGroup;//是否是军团
    private MemberFragment memberFragment;
    public DynamicFragment dynamicFragment;
    private NoticeFragment noticeFragment;
    public boolean isLeader;//当前用户是否是队长
    public String leaderId;//队长id
    private String companyName;
    private boolean isInvite;
    private boolean isHeader;
    private String parentId;
    private String companyId;
    private String logo;
    private List<Uri> avatar = new ArrayList<>();
    private int REQUEST_CODE_CHOOSE = 23;
    private HandOverTeamPoppupWindow poppupWindow;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_team_v2;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        targetId = getIntent().getStringExtra(ActivityCompat.TEAM_ID);
        if (!TextUtils.isEmpty(targetId)) {
            rci_team_logo.setEnabled(false);
        } else {
            rci_team_logo.setEnabled(true);
            targetId = "";
        }
        isTeamGroup = getIntent().getBooleanExtra(ActivityCompat.TeamGroup, false);
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(this, new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                ll_title.setPadding(0, CommonUtil.getStatusBarHeight(MyTeamActivityV2.this), 0, 0);
            }
        });
        LinearLayoutManager layoutManager = new GridLayoutManager(this, 3);
        rvTitle.setLayoutManager(layoutManager);
        myteamTypeNameAdapter = new MyteamTypeNameAdapter(this);
        rvTitle.setAdapter(myteamTypeNameAdapter);
        stringList.clear();
        for (int i = 0; i < typeNames.length; i++) {
            stringList.add(typeNames[i]);
        }
        myteamTypeNameAdapter.setNewData(stringList);
        initSportsTypeName();
        myteamTypeNameAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                myteamTypeNameAdapter.setCheckPosition(position);
                myteamTypeNameAdapter.notifyDataSetChanged();
                viewPager.setCurrentItem(position);
            }
        });

        initData();
    }

    private void initData() {
        showDialog();
        String targetIdCompany = "?targetId=%s";
        new CompanyAPI().getMemberList(String.format(targetIdCompany, targetId), new BaseResultCallback<MemberEntity>() {
            @Override
            public void onResponse(MemberEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null) {
                        entity = response.data;
                        String text = "<font color ='#333333'>%s/<font/>%s";
                        tv_team_count.setText(Html.fromHtml(String.format(text, response.data.memberCount, response.data.limitNumber)));
                        tv_team_hz.setText(response.data.totalTinder + "");
                        tv_team_totalContribute.setText(response.data.totalContribute + "%");

                        companyName = response.data.team.companyName;
                        companyId = response.data.team.companyId;
                        parentId = response.data.team.parentId;
                        logo = response.data.team.logo;
                        isLeader = response.data.leader.userId.equals(UserAPI.getUserId());
                        //队长
                        leaderId = response.data.leader.userId;
                        if (!TextUtils.isEmpty(leaderId) && leaderId.equals(UserAPI.getUserId())) {
                            tv_team_name.setCompoundDrawablesWithIntrinsicBounds(null, null, CommonUtil.getDrawable(R.mipmap.ico_editing), null);
                        } else
                            tv_team_name.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);

                        GlideUtils.loadImage(MyTeamActivityV2.this, response.data.team.logo, rci_team_logo);
                        tv_team_name.setText(response.data.team.companyName);

                        if (response.data.teamMemberList != null) {
                            poppupWindow = HandOverTeamPoppupWindow.getInstance(MyTeamActivityV2.this, response.data.teamMemberList);
                        }

                        memberFragment.initData();
                        dynamicFragment.initData();
                        noticeFragment.initData();
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }

    private void initSportsTypeName() {
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                if (position == 0) {
                    memberFragment = (MemberFragment) MemberFragment.newInstance();
                    return memberFragment;
                } else if (position == 1) {
                    dynamicFragment = (DynamicFragment) DynamicFragment.newInstance();
                    return dynamicFragment;
                } else if (position == 2) {
                    noticeFragment = (NoticeFragment) NoticeFragment.newInstance();
                    return noticeFragment;
                } else {
                    return null;
                }
            }

            @Override
            public int getCount() {
                return stringList.size();
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                myteamTypeNameAdapter.setCheckPosition(position);
                myteamTypeNameAdapter.notifyDataSetChanged();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @OnClick({R.id.top_btn_left, R.id.top_btn_right, R.id.tv_team_name, R.id.rci_team_logo, R.id.tv_invit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.top_btn_right:
                TeamPopupWindow window = TeamPopupWindow.getInstance(MyTeamActivityV2.this, isLeader);
                window.setOnClick(new TeamPopupWindow.OnClick() {
                    @Override
                    public void change() {
                        window.dismiss();
                        if (!TextUtils.isEmpty(leaderId) && leaderId.equals(UserAPI.getUserId()) && !isInvite) {
                            showPopup();
                        } else {
                            Intent intent1 = new Intent(MyTeamActivityV2.this, CheckTeamActivity.class);
                            intent1.putExtra("companyId", parentId);
                            intent1.putExtra("type", 1);
                            startActivity(intent1);
                        }
                    }

                    @Override
                    public void transfer() {
                        window.dismiss();
                        showPopup();
                    }

                    @Override
                    public void add() {
                        Intent intent = new Intent(MyTeamActivityV2.this, CrateCorpsActivity.class);
                        intent.putExtra("parentId", companyId);
                        startActivity(intent);
                        window.dismiss();
                    }

                    @Override
                    public void manager() {
                        if (entity.teamMemberList != null && entity.teamMemberList.size() > 0) {
                            window.dismiss();
                            poppupWindow = HandOverTeamPoppupWindow.getInstance(MyTeamActivityV2.this,
                                    entity.teamMemberList, HandOverTeamPoppupWindow.TYPE_MANAGER);
                            poppupWindow.show();
                            poppupWindow.setKickOut(new HandOverTeamPoppupWindow.KickOut() {
                                @Override
                                public void kickOut(String userId, String userName, String headerUrl) {
                                    poppupWindow.dismiss();
                                    KickOutPopupWindow kickOutPopupWindow = KickOutPopupWindow.getInstance(MyTeamActivityV2.this
                                            , userId, userName, headerUrl);
                                    kickOutPopupWindow.setKickOut(new KickOutPopupWindow.KickOut() {
                                        @Override
                                        public void kickOut() {
                                            kickOuts(userId, userName);
                                            kickOutPopupWindow.dismiss();
                                        }
                                    });
                                    kickOutPopupWindow.show();
                                }
                            });
                        } else {
                            ToastUtils.showShort("队伍中没有队员~");
                        }
                    }
                });
                window.show(top_btn_right);
                break;
            case R.id.tv_team_name:
                if ((!TextUtils.isEmpty(leaderId) && leaderId.equals(UserAPI.getUserId())) || isTeamGroup) {
                    showPupop();
                }
                break;
            case R.id.rci_team_logo:
                if ((!TextUtils.isEmpty(leaderId) && leaderId.equals(UserAPI.getUserId())) || isTeamGroup) {
                    isHeader = true;
                    onPermission();
                }
                break;
            case R.id.tv_invit:
                startActivity(new Intent(MyTeamActivityV2.this, InviteFriendsActivity.class));
                break;
        }
    }

    /**
     * 踢出团队
     *
     * @param userId
     */
    private void kickOuts(String userId, String userName) {
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("userId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new CompanyAPI().postKickOut(object.toString(), new BaseResultCallback<BaseResponseEntity>() {
            @Override
            public void onResponse(BaseResponseEntity response) {
                dismissDialog();
                if (response.getCode() == 0) {
                    initData();
                    ToastUtils.showShort("踢出 " + userName + " 成功");
                    EventBus.getDefault().post(new EventBusEntity(EventBusEntity.CODE_106));
                }
            }
        });
    }

    private void showPopup() {
        String usInfo = "确定选择 %s 为新队长，你将自动放弃群主身份。";
        if (poppupWindow != null) {
            if (entity.teamMemberList != null) {
                poppupWindow = HandOverTeamPoppupWindow.getInstance(MyTeamActivityV2.this, entity.teamMemberList);
            }
            poppupWindow.show();
            poppupWindow.setOnHandOverListener(new HandOverTeamPoppupWindow.OnHandOverListener() {
                @Override
                public void onHandOver(String userId, String userName) {
                    CommonDialog.getInstance(MyTeamActivityV2.this, "", String.format(usInfo, userName), "取消", "确定", 0).setOnClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onSendListener() {

                        }

                        @Override
                        public void onDismiss() {
                            onSure(userId);
                        }
                    });
                }
            });
        }
    }

    private void onSure(String userId) {
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("teamName", companyName);
            object.put("leader", userId);
            object.put("teamId", companyId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new CompanyAPI().createOrEditingTeam(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    dismissDialog();
                    poppupWindow.dismiss();
                    Intent intent1 = new Intent(MyTeamActivityV2.this, CheckTeamActivity.class);
                    intent1.putExtra("companyId", parentId);
                    intent1.putExtra("type", 1);
                    startActivity(intent1);
                } else {
                    ToastUtils.showShort(response.getMessage());
                }

            }
        });
    }

    /**
     * 获取拍照权限
     */
    private void requestCamera() {
        UiUtil.getImageSelectorConfig(this, REQUEST_CODE_CHOOSE);
    }

    @SuppressLint("WrongConstant")
    private void onPermission() {
        //请求动态权限
        PermissionUtils.permission(
                PermissionConstants.STORAGE,
                PermissionConstants.CAMERA,
                PermissionConstants.WRITE_EXTERNAL_STORAGE,
                PermissionConstants.ACCESS_COARSE_LOCATION)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        requestCamera();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                    }
                })
                .request();
    }

    AddCorpsPoppupWindow addCorpsPoppupWindow;

    private void showPupop() {
        addCorpsPoppupWindow = AddCorpsPoppupWindow.getInstance(this, companyName);
        addCorpsPoppupWindow.setOnHozonClickListener(new AddCorpsPoppupWindow.OnHozonClickListener() {
            @Override
            public void onHozomClick(String corpsName) {
                companyName = corpsName;
                onAddCorps();
            }
        });
        addCorpsPoppupWindow.show();

    }

    private void onAddCorps() {
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("teamName", companyName);
            object.put("teamId", companyId);
            object.put("logo", logo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new CompanyAPI().createOrEditingTeam(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    dismissDialog();
                    tv_team_name.setText(companyName);
                    if (addCorpsPoppupWindow != null) {
                        addCorpsPoppupWindow.dismiss();
                    }
                    EventBus.getDefault().post(new EventBusEntity(EventBusEntity.CODE_106));
                } else {
                    ToastUtils.showShort(response.getMessage());
                }

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                avatar = Matisse.obtainResult(data);
                if (avatar != null && avatar.size() > 0) {
                    Log.e("OnActivityResult ", String.valueOf(avatar.get(0)));
                    GlideUtils.loadImage(MyTeamActivityV2.this, avatar.get(0).toString(), rci_team_logo);
                    File file = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        file = CommonUtil.uriToFileApiQ(this, avatar.get(0));
                    } else {
                        file = CommonUtil.uri2File(this, avatar.get(0));
                    }
                    updateByImgUrl(file);
                }
            }
        }
    }

    private void updateByImgUrl(File imaUrl) {
        Log.e("OnActivityResult2 ", imaUrl.toString());
        TreeMap<String, String> mapType = new TreeMap<>();
        mapType.put("type", "headImg");
//        File file = ScreenShotHelper.compressImage2(CommonUtil.getImage(imaUrl.getPath()), this);
        TreeMap<String, File> mapFile = new TreeMap<>();
        mapFile.put("file", imaUrl);
        new UserAPI().putFile(mapType, mapFile, new BaseResultCallback<PictrueEntity>() {
            @Override
            public void onResponse(PictrueEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("headImgUrl", response.data.url);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String headUrl = bundle.getString("headImgUrl");
                    logo = headUrl;
                    onAddCorps();
                    break;
            }
        }
    };
}
